import { ConflictException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Repository } from 'typeorm';

import { Role } from '@src/role/entity/role.entity';

import { User } from './entity/user.entity';
import { UserCreateReqDto } from './dto/user-create.req.dto';
import { UserRepository } from './user.repository';
import { UserListReqDto } from './dto/user-list.req.dto';

@Injectable()
export class UserService {
  constructor(
    private readonly userRepo: UserRepository,
    @InjectRepository(Role)
    private readonly roleRepo: Repository<Role>,
  ) {}

  async create(dto: UserCreateReqDto): Promise<User> {
    const count = await this.userRepo.countByUsername(dto.username);
    if (count > 0) {
      throw new ConflictException('用户名已存在');
    }

    const roles = dto.roleIds?.length
      ? await this.roleRepo.findBy({ id: In(dto.roleIds) })
      : [];
    const user = this.userRepo.create({ ...dto, roles });
    return this.userRepo.save(user);
  }

  async list(dto: UserListReqDto) {
    return this.userRepo.findAndCountByConditions(dto);
  }

  async findOneByUsername(username: string): Promise<User | null> {
    return this.userRepo.findOne({ where: { username } });
  }
}
